<template>
  <view class="payment-cycle-container">
    <z-paging ref="paging" v-model="paymentList" @query="queryList" :auto="false" :refresher-enabled="true"
      :loading-more-enabled="true" :empty-view-text="'暂无数据'" class="list-paging">
      <template #top>
        <!-- 页面标题 -->
        <view class="page-header">
          <view class="header-title">总体缴费周期统计</view>
        </view>
      </template>

      
        <!-- 时间筛选 -->
        <view class="filter-section">
          <view class="time-filter">
            <view v-for="(item, index) in timeFilters" :key="index"
              :class="['filter-item', { active: currentTimeFilter === item.value }]"
              @click="handleTimeFilterChange(item.value)">
              {{ item.label }}
            </view>
          </view>

          <!-- 日期选择器 -->
          <view class="date-picker" @click="showDatePicker = true">
            <text>{{ formatDateRange }}</text>
            <image src="/static/icons/calendar-icon.svg" style="width: 18px; height: 18px;"></image>
          </view>
        </view>

        <!-- 数据卡片 -->
        <view class="data-cards">
          <view class="data-card">
            <view class="card-title">应收金额</view>
            <view class="card-value">{{ formatMoney(paymentData.receivable) }}</view>
          </view>
          <view class="data-card">
            <view class="card-title">总实收</view>
            <view class="card-value">{{ formatMoney(paymentData.totalReceived) }}</view>
          </view>
          <view class="data-card">
            <view class="card-title">本期即缴</view>
            <view class="card-value">{{ formatMoney(paymentData.currentPeriod) }}</view>
          </view>
          <view class="data-card">
            <view class="card-title">历史欠费</view>
            <view class="card-value">{{ formatMoney(paymentData.historicalDebt) }}</view>
          </view>
          <view class="data-card">
            <view class="card-title">经营欠费补缴</view>
            <view class="card-value">{{ formatMoney(paymentData.operationDebt) }}</view>
          </view>
          <view class="data-card">
            <view class="card-title">实缴率</view>
            <view class="card-value">{{ formatPercent(paymentData.paidRate) }}</view>
          </view>
        </view>

        <!-- 缴费趋势图表 -->
        <view class="chart-section">
          <view class="section-title">缴费趋势</view>
          <view class="chart-container" id="paymentChart">
            <qiun-data-charts 
              v-if="chartData.length > 0" 
              type="line" 
              :opts="chartOpts" 
              :chartData="seriesData" 
              :canvas2d="true"
              :background="'#FFFFFF'"
              :animation="true"
              :errorShow="false"
              :loadingType="2"
              :width="chartWidth"
              :height="chartHeight"
            />
            <view v-else class="chart-placeholder">
              <text>暂无数据</text>
            </view>
          </view>
        </view>

        <!-- 缴费周期列表 -->
        <view class="list-title">缴费周期明细</view>
        <view class="list-header">
          <text class="header-item name">缴费类型</text>
          <text class="header-item">应收金额</text>
          <text class="header-item">实收金额</text>
          <text class="header-item">实缴率</text>
        </view>

        <!-- 列表内容 -->
        <view v-for="(item, index) in paymentList" :key="index" class="list-item" @click="handlePaymentItemClick(item)">
          <text class="item-value name">{{ item.name }}</text>
          <text class="item-value">{{ formatMoney(item.receivable) }}</text>
          <text class="item-value">{{ formatMoney(item.received) }}</text>
          <text class="item-value">{{ formatPercent(item.paidRate) }}</text>
        </view>
    </z-paging>

    <!-- 日期选择弹窗 -->
    <up-datetime-picker 
      :show="showDatePicker" 
      :mode="datePickerType" 
      v-model="dateRange" 
      closeOnClickOverlay 
      @confirm="handleDateConfirm"
      @cancel="showDatePicker = false"
      @close="showDatePicker = false"
    />
  </view>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { formatDate, formatMoney, formatPercent } from '@/utils/index'
import qiunDataCharts from '@/components/qiun-data-charts/qiun-data-charts.vue'

// 时间筛选选项
const timeFilters = [
  { label: '日', value: 'day' },
  { label: '周', value: 'week' },
  { label: '月', value: 'month' },
  { label: '年', value: 'year' }
]

// 当前选中的时间筛选
const currentTimeFilter = ref('day')

// 日期选择器相关
const showDatePicker = ref(false)
const datePickerType = computed(() => {
  switch (currentTimeFilter.value) {
    case 'day':
      return 'date'
    case 'week':
      return 'datetime-range'
    case 'month':
      return 'year-month'
    case 'year':
      return 'year'
    default:
      return 'date'
  }
})

// 日期范围
const today = new Date()
const dateRange = ref([today, today])

// 格式化日期范围显示
const formatDateRange = computed(() => {
  switch (currentTimeFilter.value) {
    case 'day':
      return formatDate(dateRange.value[0], 'yyyy-MM-dd')
    case 'week':
      return `${formatDate(dateRange.value[0], 'yyyy-MM-dd')} 至 ${formatDate(dateRange.value[1], 'yyyy-MM-dd')}`
    case 'month':
      return formatDate(dateRange.value[0], 'yyyy-MM')
    case 'year':
      return formatDate(dateRange.value[0], 'yyyy')
    default:
      return formatDate(dateRange.value[0], 'yyyy-MM-dd')
  }
})

// 缴费数据
const paymentData = ref({
  receivable: 0,
  totalReceived: 0,
  currentPeriod: 0,
  historicalDebt: 0,
  operationDebt: 0,
  paidRate: 0
})

// 缴费列表数据
const paymentList = ref([])

// 图表数据
const chartData = ref([])

// 图表尺寸
const chartWidth = ref(0)
const chartHeight = ref(200)

// 图表配置
const chartOpts = ref({
  color: ['#667eea'],
  padding: [15, 15, 15, 15],
  legend: {
    show: false
  },
  xAxis: {
    boundaryGap: true,
    axisLine: true,
    splitLine: true,
    itemCount: 5 // 控制X轴显示的刻度数量
  },
  yAxis: {
    splitLine: true,
    axisLine: true,
    format: 'currency',
    formatter: (val) => {
      return val.toFixed(1)
    },
    decimal: 1 // 设置小数点位数为1位
  },
  extra: {
    line: {
      type: 'straight',
      width: 2,
      activeType: 'hollow'
    }
  }
})

// 转换为echarts数据格式
const seriesData = computed(() => {
  if (chartData.value.length === 0) return { categories: [], series: [] }
  
  return {
    categories: chartData.value.map(item => item.label),
    series: [
      {
        name: '缴费金额',
        data: chartData.value.map(item => parseFloat(item.value.toFixed(1)))
      }
    ]
  }
})

// 处理时间筛选变化
const handleTimeFilterChange = (filter) => {
  currentTimeFilter.value = filter
  // 根据筛选类型重置日期范围
  resetDateRange()
  // 重新获取数据
  fetchPaymentData()
  // 更新图表数据
  generateChartData()
}

// 重置日期范围
const resetDateRange = () => {
  const now = new Date()
  switch (currentTimeFilter.value) {
    case 'day':
      dateRange.value = [now, now]
      break
    case 'week':
      const startOfWeek = new Date(now)
      startOfWeek.setDate(now.getDate() - now.getDay())
      const endOfWeek = new Date(startOfWeek)
      endOfWeek.setDate(startOfWeek.getDate() + 6)
      dateRange.value = [startOfWeek, endOfWeek]
      break
    case 'month':
      const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)
      dateRange.value = [startOfMonth, startOfMonth]
      break
    case 'year':
      const startOfYear = new Date(now.getFullYear(), 0, 1)
      dateRange.value = [startOfYear, startOfYear]
      break
  }
}

// 处理日期确认
const handleDateConfirm = (e) => {
  // up-datetime-picker已经通过v-model自动更新dateRange值
  // 关闭弹窗也由组件自动处理
  fetchPaymentData()
  generateChartData()
}

// 处理缴费列表项点击
const handlePaymentItemClick = (payment) => {
  // 可以跳转到详情页或者展示更多信息
  uni.showToast({
    title: `查看${payment.name}详情`,
    icon: 'none'
  })
}

// 分页组件引用
const paging = ref(null)

// 查询列表数据
const queryList = (pageNo, pageSize) => {
  // 构建请求参数
  const params = {
    timeType: currentTimeFilter.value,
    startDate: formatDate(dateRange.value[0], 'yyyy-MM-dd'),
    endDate: formatDate(dateRange.value[1], 'yyyy-MM-dd'),
    pageNo: pageNo,
    pageSize: pageSize
  }

  // 模拟请求延迟
  setTimeout(() => {
    // 生成模拟数据
    const data = generatePaymentListData()
    paging.value.complete(data)

    // 更新统计摘要
    updateSummary(data)
  }, 500)
}

// 更新统计摘要
const updateSummary = (data) => {
  // 根据不同的时间维度生成不同的模拟数据
  let baseReceivable = 0
  let baseReceived = 0
  let baseCurrentPeriod = 0
  let baseHistoricalDebt = 0
  let baseOperationDebt = 0

  switch (currentTimeFilter.value) {
    case 'day':
      baseReceivable = 18000 + Math.random() * 6000
      baseReceived = baseReceivable * (0.7 + Math.random() * 0.2)
      baseCurrentPeriod = baseReceived * (0.6 + Math.random() * 0.2)
      baseHistoricalDebt = baseReceived * (0.2 + Math.random() * 0.1)
      baseOperationDebt = baseReceived * (0.1 + Math.random() * 0.1)
      break
    case 'week':
      baseReceivable = 90000 + Math.random() * 25000
      baseReceived = baseReceivable * (0.75 + Math.random() * 0.15)
      baseCurrentPeriod = baseReceived * (0.65 + Math.random() * 0.15)
      baseHistoricalDebt = baseReceived * (0.2 + Math.random() * 0.1)
      baseOperationDebt = baseReceived * (0.1 + Math.random() * 0.1)
      break
    case 'month':
      baseReceivable = 350000 + Math.random() * 120000
      baseReceived = baseReceivable * (0.8 + Math.random() * 0.15)
      baseCurrentPeriod = baseReceived * (0.7 + Math.random() * 0.15)
      baseHistoricalDebt = baseReceived * (0.2 + Math.random() * 0.1)
      baseOperationDebt = baseReceived * (0.1 + Math.random() * 0.05)
      break
    case 'year':
      baseReceivable = 4000000 + Math.random() * 1200000
      baseReceived = baseReceivable * (0.85 + Math.random() * 0.1)
      baseCurrentPeriod = baseReceived * (0.75 + Math.random() * 0.15)
      baseHistoricalDebt = baseReceived * (0.15 + Math.random() * 0.1)
      baseOperationDebt = baseReceived * (0.1 + Math.random() * 0.05)
      break
  }

  // 计算比率
  const paidRate = baseReceived / baseReceivable

  // 更新总收入数据
  paymentData.value = {
    receivable: baseReceivable,
    totalReceived: baseReceived,
    currentPeriod: baseCurrentPeriod,
    historicalDebt: baseHistoricalDebt,
    operationDebt: baseOperationDebt,
    paidRate: paidRate
  }
}

// 生成缴费列表数据
const generatePaymentListData = () => {
  // 缴费类型
  const paymentTypes = [
    { id: 1, name: '停车费' },
    { id: 2, name: '物业费' },
    { id: 3, name: '水电费' },
    { id: 4, name: '租金' },
    { id: 5, name: '其他费用' }
  ]

  const baseReceivable = paymentData.value.receivable
  const paidRate = paymentData.value.paidRate

  return paymentTypes.map(type => {
    // 为每个缴费类型生成随机数据，但保持总和与总收入一致
    const factor = 0.5 + Math.random() * 1.5 // 随机因子，使数据分布不均匀
    const typeReceivable = baseReceivable / paymentTypes.length * factor
    const typeReceived = typeReceivable * (paidRate * 0.9 + Math.random() * 0.2) // 保持在总体实缴率附近

    return {
      ...type,
      receivable: typeReceivable,
      received: typeReceived,
      paidRate: typeReceived / typeReceivable,
      currentPeriod: typeReceived * (0.6 + Math.random() * 0.2),
      historicalDebt: typeReceived * (0.2 + Math.random() * 0.1),
      operationDebt: typeReceived * (0.1 + Math.random() * 0.1)
    }
  })
}

// 获取缴费数据
const fetchPaymentData = () => {
  // 重新加载列表数据
  if (paging.value) {
    paging.value.reload()
  }
}

// 获取图表容器宽度
const getChartContainerWidth = () => {
  // 使用uni.createSelectorQuery获取图表容器宽度
  const query = uni.createSelectorQuery()
  query.select('#paymentChart').boundingClientRect(data => {
    if (data) {
      chartWidth.value = data.width || 300
    }
  }).exec()
}

// 生成图表数据
const generateChartData = () => {
  const data = []
  let labels = []

  // 生成随机数并保留1位小数的辅助函数
  const generateRandomValue = (min, max) => {
    return parseFloat((Math.random() * (max - min) + min).toFixed(1))
  }

  switch (currentTimeFilter.value) {
    case 'day':
      // 按3小时间隔生成数据
      for (let i = 0; i < 24; i += 3) {
        data.push({
          label: `${i}:00`,
          value: generateRandomValue(1200, 7000)
        })
      }
      break
    case 'week':
      // 按天生成数据，隔天显示
      labels = ['周一', '周三', '周五', '周日']
      for (let i = 0; i < labels.length; i++) {
        data.push({
          label: labels[i],
          value: generateRandomValue(6000, 22000)
        })
      }
      break
    case 'month':
      // 按5天间隔生成数据
      for (let i = 1; i <= 6; i++) {
        data.push({
          label: `${i * 5}日`,
          value: generateRandomValue(10000, 30000)
        })
      }
      break
    case 'year':
      // 按季度生成数据
      labels = ['1月', '3月', '6月', '9月', '12月']
      for (let i = 0; i < labels.length; i++) {
        data.push({
          label: labels[i],
          value: generateRandomValue(120000, 450000)
        })
      }
      break
  }

  chartData.value = data

  // 获取图表容器宽度
  nextTick(() => {
    getChartContainerWidth()
  })
}

// 页面加载时初始化
onMounted(() => {
  resetDateRange()
  // 初始化数据
  updateSummary([])
  // 延迟执行，确保组件已挂载
  nextTick(() => {
    if (paging.value) {
      paging.value.reload()
    }
    // 获取图表容器宽度
    getChartContainerWidth()
    // 生成图表数据
    generateChartData()
  })
})
</script>

<style lang="scss" scoped>
.payment-cycle-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

.list-paging {
  flex: 1;
  height: 100%;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx 30rpx 30rpx;
  color: white;

  .header-title {
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
  }
}

.filter-section {
  background-color: white;
  padding: 20rpx;
  margin-bottom: 20rpx;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

  .time-filter {
    display: flex;
    justify-content: space-around;
    margin-bottom: 20rpx;

    .filter-item {
      padding: 10rpx 30rpx;
      border-radius: 30rpx;
      font-size: 28rpx;
      color: #666;

      &.active {
        background-color: #667eea;
        color: white;
      }
    }
  }

  .date-picker {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 10rpx;
    font-size: 28rpx;
    color: #333;

    image {
      margin-left: 10rpx;
    }
  }
}

.data-cards {
  display: flex;
  flex-wrap: wrap;
  padding: 10rpx;

  .data-card {
    width: calc(50% - 20rpx);
    margin: 10rpx;
    background-color: white;
    border-radius: 10rpx;
    padding: 20rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

    .card-title {
      font-size: 24rpx;
      color: #666;
      margin-bottom: 10rpx;
    }

    .card-value {
      font-size: 32rpx;
      color: #333;
      font-weight: bold;
    }
  }
}

.chart-section {
  background-color: white;
  margin: 20rpx;
  border-radius: 10rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

  .section-title {
    font-size: 30rpx;
    color: #333;
    margin-bottom: 20rpx;
    font-weight: bold;
  }

  .chart-container {
    height: 400rpx;
    width: 100%;
    position: relative;
    
    :deep(.qiun-charts) {
      width: 100%;
      height: 100%;
    }
  }

  .chart-placeholder {
    height: 300rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f9f9f9;
    border-radius: 8rpx;

    text {
      color: #999;
      font-size: 28rpx;
    }
  }
}

.list-title {
  font-size: 30rpx;
  color: #333;
  margin: 20rpx 20rpx 10rpx;
  font-weight: bold;
  background-color: white;
  padding: 20rpx;
  border-radius: 10rpx 10rpx 0 0;
}

.list-header {
  display: flex;
  padding: 15rpx 20rpx;
  background-color: white;
  margin: 0 20rpx;
  border-bottom: 1rpx solid #eee;

  .header-item {
    flex: 1;
    font-size: 26rpx;
    color: #666;
    text-align: center;

    &.name {
      flex: 1.5;
      text-align: left;
    }
  }
}

.list-item {
  display: flex;
  padding: 20rpx;
  background-color: white;
  margin: 0 20rpx 2rpx;
  border-bottom: 1rpx solid #eee;

  &:last-child {
    border-bottom: none;
    border-radius: 0 0 10rpx 10rpx;
    margin-bottom: 20rpx;
  }

  .item-value {
    flex: 1;
    font-size: 26rpx;
    color: #333;
    text-align: center;

    &.name {
      flex: 1.5;
      text-align: left;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}
</style>